﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DiscoveryLogic.DataServices.DataSources;
using DiscoveryLogic.UI.Layouts.ContentScreens;
using DiscoveryLogic.UI.Layouts.CustomEventArgs;

namespace DiscoveryLogic.UI.Layouts
{
    public partial class DashboardForm : UserControl
    {

        #region Private Variables
        private List<UserControl> screens;
        private int currentScreen;
        private const double mainContentTopMargin = 100;
        private const double mainContentLeftMargin = 200;
        private const string screenPrefix = "Screen_";
        #endregion

        public DashboardForm()
        {
            InitializeComponent();
            try
            {
                screens = new List<UserControl>();

                this.Loaded += new RoutedEventHandler(Page_Loaded);

                App.Current.Host.Content.Resized += new EventHandler(Content_Resized);

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        #region public methods
        void Content_Resized(object sender, EventArgs e)
        {
            ScaleContainer(App.Current.Host.Content.ActualHeight, App.Current.Host.Content.ActualWidth);
            //if (App.Current.Host.Content.ActualHeight > 0)
            //{
            //    double width = (App.Current.Host.Content.ActualHeight / 744) * 1005;

            //    App.Current.Host.Width = width; 

            //    // slPlugin.width = (slPlugin.content.actualHeight / 744) * 1005;
            //}
        }

        protected virtual void OnFullScreenChanged(object sender, EventArgs e)
        {
            OnContentResized(sender, e);

        }

        protected virtual void OnContentResized(object sender, EventArgs e)
        {
            this.ScaleContainer(Application.Current.Host.Content.ActualHeight, Application.Current.Host.Content.ActualWidth);
        }

        public void Page_Loaded(object o, EventArgs e)
        {
            try
            {
                Application.Current.Host.Content.Resized += new EventHandler(OnContentResized);
                Application.Current.Host.Content.FullScreenChanged += new EventHandler(OnFullScreenChanged);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            HtmlPage.RegisterScriptableObject("DashboardForm", this);

            if (App.Current.Host.IsLoaded)
            {
                //this.ScaleContainer(App.Current.Host.Content.ActualWidth, App.Current.Host.Content.ActualHeight);
                //HtmlPage.Window.Invoke("ResizeSLContainer");
            }

            // Capture Canvas element
            // topCanvas = (Canvas)o;

            // Create and Initialize View 360
            screens.Add(new View360(this));
            currentScreen = 0;

            // Set properties of View360
            screens[currentScreen].SetValue(Canvas.ZIndexProperty, 2);
            screens[currentScreen].SetValue(Canvas.LeftProperty, mainContentLeftMargin);
            screens[currentScreen].SetValue(Canvas.TopProperty, mainContentTopMargin);
            screens[currentScreen].SetValue(Canvas.NameProperty, screenPrefix + currentScreen.ToString());

            ((View360)screens[0]).innerContainerPanel.ScaleX = DashboardFormScale.ScaleX;
            ((View360)screens[0]).innerContainerPanel.ScaleY = DashboardFormScale.ScaleY;
            ((View360)screens[0]).outerContainerPanel.ScaleX = DashboardFormScale.ScaleX;
            ((View360)screens[0]).outerContainerPanel.ScaleY = DashboardFormScale.ScaleY;

            // Add View360 to Canvas                
            this.Root.Children.Add(screens[currentScreen]);
        }

        [ScriptableMember]
        public void ScaleContainer(double containerHeight, double containerWidth)
        {
            if (containerHeight != 0 && containerWidth != 0)
            {

                if (DashboardFormScale != null)
                {
                    double scale = Math.Min(containerHeight / 744, containerWidth / 1005);
                    DashboardFormScale.ScaleX = scale;
                    DashboardFormScale.ScaleY = scale;

                    if (screens.Count > 0 && screens[0] != null)
                    {
                        ((View360)screens[0]).innerContainerPanel.ScaleX = DashboardFormScale.ScaleX;
                        ((View360)screens[0]).innerContainerPanel.ScaleY = DashboardFormScale.ScaleY;
                        ((View360)screens[0]).outerContainerPanel.ScaleX = DashboardFormScale.ScaleX;
                        ((View360)screens[0]).outerContainerPanel.ScaleY = DashboardFormScale.ScaleY;
                    }
                }
            }
        }

        #endregion

        #region Mouse Events

        protected void NavPanel_MouseEnter(object sender, MouseEventArgs e)
        {
            this.navPanelOpen.Begin();
        }

        protected void NavPanel_MouseLeave(object sender, EventArgs e)
        {
            this.navPanelClose.Begin();
        }

        protected void MouseEnter_Hand(object sender, EventArgs e)
        {
            ((FrameworkElement)sender).Cursor = Cursors.Hand;
        }

        protected void MouseLeave_Arrow(object sender, EventArgs e)
        {
            ((FrameworkElement)sender).Cursor = Cursors.Arrow;
        }

        protected void MouseEnter_Nav360(object sender, EventArgs e)
        {
            ((FrameworkElement)sender).Cursor = Cursors.Hand;

            Canvas nav360Disc = this.FindName("Disc") as Canvas;
            nav360Disc.SetValue(Canvas.TopProperty, (double)nav360Disc.GetValue(Canvas.TopProperty) - 2);

            Canvas nav360Man = this.FindName("ManIcon") as Canvas;
            nav360Man.SetValue(Canvas.TopProperty, (double)nav360Man.GetValue(Canvas.TopProperty) - 2);
        }

        protected void MouseLeave_Nav360(object sender, EventArgs e)
        {
            ((FrameworkElement)sender).Cursor = Cursors.Arrow;

            Canvas nav360Disc = this.FindName("Disc") as Canvas;
            nav360Disc.SetValue(Canvas.TopProperty, (double)nav360Disc.GetValue(Canvas.TopProperty) + 2);

            Canvas nav360Man = this.FindName("ManIcon") as Canvas;
            nav360Man.SetValue(Canvas.TopProperty, (double)nav360Man.GetValue(Canvas.TopProperty) + 2);
        }

        protected void NavButton0_Click(object sender, EventArgs e)
        {
            // Load Bill Pay            
            LoadScreen(typeof(BillPay), null);

        }

        protected void NavButton1_Click(object sender, EventArgs e)
        {
            // Load Enrollment
            LoadScreen(typeof(Enrollment), null);
        }

        protected void NavButton2_Click(object sender, EventArgs e)
        {

        }

        protected void NavButton3_Click(object sender, EventArgs e)
        {

        }

        protected void Nav360_Click(object sender, EventArgs e)
        {

            Storyboard flyOut = this.FindName("my360Flyout") as Storyboard;
            flyOut.Begin();
        }

        protected void Ad_MouseEnter(object sender, EventArgs e)
        {
            if (screens[currentScreen].GetType() == typeof(MortgageCalculator))
            {
                ((FrameworkElement)sender).Cursor = Cursors.Hand;
            }
        }

        protected void Ad_MouseClick(object sender, EventArgs e)
        {
            if (screens[currentScreen].GetType() == typeof(MortgageCalculator))
            {
                LoadScreen(typeof(Heloc), null);
            }
        }

        #endregion

        #region Helper Methods

        private void Nav360FlyoutAnim_Completed(object sender, EventArgs e)
        {
            // Load View360
            LoadScreen(typeof(View360), null);
        }

        private void StartNav360FlyInAnimation()
        {
            Storyboard flyIn = this.FindName("my360Flyin") as Storyboard;
            flyIn.Begin();
        }

        private void LoadScreen(Type screenType, Account accountToLoad)
        {
            bool screenLoaded = false;

            // Search to see if screen has been added
            for (int i = 0; i < screens.Count; i++)
            {
                // If we find screen is loaded
                if (screens[i].GetType() == screenType)
                {

                    screenLoaded = true;

                    // Change screen
                    ChangeScreen(i);
                }
            }

            // If screen isnt loaded, then load it
            if (screenLoaded == false)
            {

                switch (screenType.Name)
                {
                    case "FiveTwentyNineEnrollment":
                        screens.Add(new FiveTwentyNineEnrollment());
                        ((FiveTwentyNineEnrollment)screens[screens.Count - 1]).fiveTwentyNineEnrollmentComplete += new EventHandler(this.OnHomeClicked);
                        ((FiveTwentyNineEnrollment)screens[screens.Count - 1]).backToNewAccountMenu += new EventHandler(DashboardForm_backToNewAccountMenu);
                        break;
                    case "TradeHistory":
                        screens.Add(new TradeHistory(this));
                        break;
                    case "RetirementPlanner":
                        screens.Add(new RetirementPlanner());
                        break;
                    case "Enrollment":
                        Enrollment enrollmentScreen = new Enrollment();
                        screens.Add(enrollmentScreen);
                        enrollmentScreen.enrollmentComplete += new EventHandler(Nav360_Click);
                        enrollmentScreen.new529Enrollment += new EventHandler(OnNew529Enrollment);
                        break;
                    case "BillPay":
                        screens.Add(new BillPay());
                        ((BillPay)screens[screens.Count - 1]).GoHome += new EventHandler(this.OnHomeClicked);
                        break;
                    case "Heloc":
                        screens.Add(new Heloc());
                        break;
                    case "MortgageCalculator":
                        screens.Add(new MortgageCalculator());
                        break;
                    case "Portfolio":
                        screens.Add(new Portfolio());
                        break;

                    case "View360":
                        screens.Add(new View360(this));
                        break;
                    default:
                        return;
                }

                screens[screens.Count - 1].SetValue(Canvas.NameProperty, screenPrefix + (screens.Count - 1).ToString());
                this.Root.Children.Add(screens[screens.Count - 1]);
                ChangeScreen(screens.Count - 1);
            }
        }

        private void ChangeScreen(int index)
        {
            // Load Heloc
            // Special case for Heloc because it pops up over current screen
            if (screens[index].GetType() == typeof(Heloc))
            {
                screens[index].SetValue(Canvas.ZIndexProperty, 3);
                screens[index].SetValue(Canvas.LeftProperty, mainContentLeftMargin - 90);
                screens[index].SetValue(Canvas.TopProperty, mainContentTopMargin + 50);

                if (screens[index] is IContentScreen)
                {
                    ((IContentScreen)screens[index]).ScreenShowActions();
                }
                screens[index].Opacity = 1;
                screens[index].Visibility = Visibility.Visible;
                ((Heloc)screens[index]).ShowCanvas();
            }
            else
            {
                // Switch off current screen
                for (int i = 0; i < screens.Count; i++)
                {
                    screens[i].Opacity = 0;
                    screens[i].Visibility = Visibility.Collapsed;
                    if (screens[i] is IContentScreen && i != index)
                    {
                        ((IContentScreen)screens[i]).ScreenHideActions();
                    }
                }

                // Show new screen
                screens[index].SetValue(Canvas.ZIndexProperty, 2);
                screens[index].SetValue(Canvas.LeftProperty, mainContentLeftMargin);
                screens[index].SetValue(Canvas.TopProperty, mainContentTopMargin);
                if (screens[index] is IContentScreen)
                    ((IContentScreen)screens[index]).ScreenShowActions();
                screens[index].Opacity = 0;
                screens[index].Visibility = Visibility.Visible;

                // Check if old scrren is 360 screen
                if (screens[currentScreen].GetType() == typeof(View360))
                {
                    StartNav360FlyInAnimation();
                }

                // Start screen fade in storyboard
                Storyboard fadeIn = this.FindName("contentFadeIn") as Storyboard;
                fadeIn.Stop();

                DoubleAnimationUsingKeyFrames fadeInAnim = this.FindName("contentFadeInAnim") as DoubleAnimationUsingKeyFrames;
                fadeInAnim.SetValue(Storyboard.TargetNameProperty, screenPrefix + index);

                fadeIn.Begin();

                // Update currentScreen index
                currentScreen = index;

                // Change ad in ad panel
                ChangeAd();
            }
        }

        private void ChangeAd()
        {
            // Change Ad in ad panel
            Random r = new Random();
            int adNum = 0;

            string accountType = screens[currentScreen].GetType().Name;

            switch (accountType)
            {
                case "FiveTwentyNineEnrollment":
                    adNum = 4;
                    break;
                case "MortgageCalculator":
                    adNum = 1;
                    break;
                case "Portfolio":
                    adNum = 3;
                    break;
                case "StatementViewer":
                    adNum = 2;
                    break;
                default:
                    adNum = r.Next(2, 4);
                    break;
            }

            Image adImage = this.FindName("AdImage") as Image;
            try
            {
                adImage.SetValue(Image.SourceProperty, "/Assets/WoodgroveAd" + adNum + ".png");
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }

        }
        #endregion

        #region Event Handlers

        public void OnAspectClicked(object sender, EventArgs e)
        {
            AccountType accountType = ((NavEventArgs)e).Account.Type;
            switch (accountType)
            {
                case AccountType.TradeHistory:
                    LoadScreen(typeof(TradeHistory), null);
                    break;
                case AccountType.RetirementPlanner:
                    LoadScreen(typeof(RetirementPlanner), null);
                    break;
                case AccountType.Checking:

                    break;
                case AccountType.Savings:

                    break;
                case AccountType.Plan401k:
                    // Load 401k account screen
                    break;
                case AccountType.FiveTwoNine:
                    // Do not load 529 enrollment
                    // The new entry point is through New Account on left menu
                    //LoadScreen(typeof(FiveTwentyNineEnrollment), null);
                    break;
                case AccountType.CreditCard:
                    // Do not load the credit card statement viewer
                    // not converted to Beta 2
                    //LoadScreen(typeof(StatementViewer), null);
                    break;
                case AccountType.Investments:
                    LoadScreen(typeof(Portfolio), null);
                    break;
                case AccountType.Mortgage:
                    LoadScreen(typeof(MortgageCalculator), null);
                    break;
                default:
                    break;
            }
        }

        public void OnHomeClicked(object sender, EventArgs e)
        {
            // Load View360
            Nav360_Click(sender, e);
        }

        private void OnNew529Enrollment(object sender, EventArgs e)
        {
            // Load 529 Account            
            LoadScreen(typeof(FiveTwentyNineEnrollment), null);
        }

        /// <summary>
        /// Back is clicked on the first screen of 529 enrollment
        /// We want to bring the user back to the new account selection screen
        /// in enrollment scenario
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DashboardForm_backToNewAccountMenu(object sender, EventArgs e)
        {
            // Load enrollment
            LoadScreen(typeof(Enrollment), null);
        }


        #endregion
    }
}
